package com.google.android.apps.iosched.ui;

import android.accounts.Account;
import android.annotation.TargetApi;
import android.app.SearchManager;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.SyncStatusObserver;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.widget.SearchView;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.google.analytics.tracking.android.EasyTracker;
import com.google.android.apps.iosched.BuildConfig;
import com.google.android.apps.iosched.Config;
import com.google.android.apps.iosched.R;
import com.google.android.apps.iosched.gcm.ServerUtilities;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.ui.gtv.GoogleTvSessionLivestreamActivity;
import com.google.android.apps.iosched.util.AccountUtils;
import com.google.android.apps.iosched.util.BeamUtils;
import com.google.android.apps.iosched.util.HelpUtils;
import com.google.android.apps.iosched.util.UIUtils;
import com.google.android.gcm.GCMRegistrar;
import com.google.api.client.googleapis.extensions.android2.auth.GoogleAccountManager;

import static com.google.android.apps.iosched.util.LogUtils.LOGD;
import static com.google.android.apps.iosched.util.LogUtils.LOGI;
import static com.google.android.apps.iosched.util.LogUtils.LOGW;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
 * Created by Alex on 13-11-29.
 */
public class HomeActivity extends BaseActivity implements ActionBar.TabListener, ViewPager.OnPageChangeListener{



    private static final String TAG = makeLogTag(HomeActivity.class);


    private Object mSyncObserverHandler;

    private MyScheduleFragment mMyScheduleFragment;
    private ExploreFragment mExploreFragment;
    private SocialStreamFragment mSocialStreamFragment;

    private ViewPager mViewPage;
    private Menu mOptionsMenu;

    private AsyncTask<Void,Void,Void> mGCMRegisterTask;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if(UIUtils.isGoogleTv(this)){
            Intent intent = new Intent(HomeActivity.this,GoogleTvSessionLivestreamActivity.class);
            startActivity(intent);
            finish();
        }

        if(isFinishing()){
            return;
        }

        UIUtils.enableDisableActivities(this);
        EasyTracker.getTracker().setContext(this);

        setContentView(R.layout.activity_home);

        FragmentManager fm = getSupportFragmentManager();

        mViewPage = (ViewPager) this.findViewById(R.id.pager);

        //当前的标题
        String homeScreenLabel;

        //小屏幕的情况下
        if(mViewPage != null){
            mViewPage.setAdapter(new HomePagerAdapter(getSupportFragmentManager()));
            mViewPage.setOnPageChangeListener(this);
            mViewPage.setPageMarginDrawable(R.drawable.grey_border_inset_lr);
            mViewPage.setPageMargin(getResources().getDimensionPixelOffset(R.dimen.page_margin_width));

            final ActionBar actionBar = getSupportActionBar();
            actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
            actionBar.addTab(actionBar.newTab().setText(R.string.title_my_schedule).setTabListener(this));
            actionBar.addTab(actionBar.newTab().setText(R.string.title_explore).setTabListener(this));
            actionBar.addTab(actionBar.newTab().setText(R.string.title_stream).setTabListener(this));

            homeScreenLabel = getString(R.string.title_my_schedule);

        } else {
            //大屏幕的情况下
            mExploreFragment = (ExploreFragment) fm.findFragmentById(R.id.fragment_tracks);
            mMyScheduleFragment = (MyScheduleFragment) fm.findFragmentById(R.id.fragment_my_schedule);
            mSocialStreamFragment = (SocialStreamFragment) fm.findFragmentById(R.id.fragment_stream);

            homeScreenLabel = "Home";
        }

        getSupportActionBar().setHomeButtonEnabled(false);
        EasyTracker.getTracker().trackView(homeScreenLabel);
        LOGD("Tracker",homeScreenLabel);

        if(savedInstanceState == null){
            triggerRefresh();
            registerGCMClient();
        }

    }

    //创建Menu
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);

        mOptionsMenu = menu;
        getSupportMenuInflater().inflate(R.menu.home,menu);
        setupSearchMenuItem(menu);

        if (!BeamUtils.isBeamUnlocked(this)){
            MenuItem beamItem = menu.findItem(R.id.menu_beam);
            if (beamItem != null){
                menu.removeItem(beamItem.getItemId());
            }
        }

        return true;
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    private void setupSearchMenuItem(Menu menu){
        MenuItem searchItem = menu.findItem(R.id.menu_search);
        if (searchItem != null && UIUtils.hasHoneycomb()){
            SearchView searchView = (SearchView) searchItem.getActionView();
            if (searchView != null) {
                SearchManager searchManager = (SearchManager) getSystemService(SEARCH_SERVICE);
                searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
            }
        }

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()){
            case R.id.menu_refresh:
                triggerRefresh();
                return true;
            case R.id.menu_search:
                if (!UIUtils.hasHoneycomb()){
                    startSearch(null,false,Bundle.EMPTY,false);
                    return true;
                }
                return true;
            case R.id.menu_about:
                HelpUtils.showAbout(this);
                return true;

            case R.id.menu_sign_out:
                AccountUtils.signOut(this);
                finish();
                return true;
            case R.id.menu_beam:

                Intent intent = new Intent(this, BeamActivity.class);
                startActivity(intent);
                return true;

        }

        return super.onOptionsItemSelected(item);
    }

    private void registerGCMClient(){
        GCMRegistrar.checkDevice(this);
        if(BuildConfig.DEBUG){
            GCMRegistrar.checkManifest(this);
        }

        final String regId = GCMRegistrar.getRegistrationId(this);
        if(TextUtils.isEmpty(regId)){
            GCMRegistrar.register(this, Config.GCM_SENDER_ID);
        }else{
            if(GCMRegistrar.isRegisteredOnServer(this)){
                LOGI(TAG,"Already registered on the GCM server");
            }

            //声明AsyncTask
            mGCMRegisterTask = new AsyncTask<Void, Void, Void>() {
                @Override
                protected Void doInBackground(Void... voids) {

                   boolean registered = ServerUtilities.register(HomeActivity.this, regId);

                    if(! registered){
                        GCMRegistrar.unregister(HomeActivity.this);
                    }
                   return null;

                }

                @Override
                protected void onPostExecute(Void aVoid) {
                    mGCMRegisterTask = null;
                }
            };
            //执行AsyncTask
            mGCMRegisterTask.execute(null,null,null);
        }
    }


    private void triggerRefresh(){

        Bundle extras = new Bundle();
        extras.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);

        if(!UIUtils.isGoogleTv(this)){
            ContentResolver.requestSync(new Account(
                    AccountUtils.getChosenAccountName(this),GoogleAccountManager.ACCOUNT_TYPE),
            ScheduleContract.CONTENT_AUTHORITY,extras);
        }
    }





    //声明周期方法
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        if (mSocialStreamFragment != null){
            getSupportFragmentManager().putFragment(outState,"stream_fragment",mSocialStreamFragment);
        }
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);

        if (mSocialStreamFragment == null){
            mSocialStreamFragment = (SocialStreamFragment) getSupportFragmentManager().getFragment(savedInstanceState,"stream_fragment");
        }
    }




    //暂停
    @Override
    protected void onPause() {
        super.onPause();

        //删除对内容提供者的状态监听
        if (mSyncObserverHandler != null){
            ContentResolver.removeStatusChangeListener(mSyncObserverHandler);
            mSyncObserverHandler = null;
        }
    }

    //恢复
    @Override
    protected void onResume() {
        super.onResume();
        mSyncStatusObserver.onStatusChanged(0);

        final int mask = ContentResolver.SYNC_OBSERVER_TYPE_PENDING | ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE;
        mSyncObserverHandler = ContentResolver.addStatusChangeListener(mask,mSyncStatusObserver);
    }


    public void setRefreshActionButtonState(boolean refreshing){
        if(mOptionsMenu == null){
            return;
        }

        final MenuItem refresItem = mOptionsMenu.findItem(R.id.menu_refresh);
        if(refreshing){
            refresItem.setActionView(R.layout.actionbar_indeterminate_progress);
        }else{
            refresItem.setActionView(null);
        }
    }

    private final SyncStatusObserver mSyncStatusObserver = new SyncStatusObserver() {
        @Override
        public void onStatusChanged(int i) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    String accountName = AccountUtils.getChosenAccountName(HomeActivity.this);
                    if(TextUtils.isEmpty(accountName)){
                        setRefreshActionButtonState(false);
                        return;
                    }

                    Account account = new Account(accountName, GoogleAccountManager.ACCOUNT_TYPE);
                    boolean syncActive = ContentResolver.isSyncActive(account,ScheduleContract.CONTENT_AUTHORITY);
                    boolean syncPending = ContentResolver.isSyncPending(account,ScheduleContract.CONTENT_AUTHORITY);
                    setRefreshActionButtonState(syncActive || syncPending);
                }
            });
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (mGCMRegisterTask != null){
            mGCMRegisterTask.cancel(true);
        }

        try {
            GCMRegistrar.onDestroy(this);
        }catch (Exception e){
            LOGW(TAG,"GCM unregistration error",e);
        }
    }

    /**
     * PagerAdapter
     */
    private class HomePagerAdapter extends FragmentPagerAdapter {

        public HomePagerAdapter(FragmentManager fm){
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            switch (position){
                case 0:
                    return (mMyScheduleFragment = new MyScheduleFragment());
                case 1:
                    return (mExploreFragment = new ExploreFragment());
                case 2:
                    return (mSocialStreamFragment = new SocialStreamFragment());
            }
            return null;
        }

        @Override
        public int getCount() {
            return 3;
        }
    }

    @Override
    public void onPageScrolled(int i, float v, int i2) {

    }

    @Override
    public void onPageSelected(int position) {
        getSupportActionBar().setSelectedNavigationItem(position);

        int titleId = -1;
        switch (position){
            case 0:
                titleId = R.string.title_my_schedule;
                break;
            case 1:
                titleId = R.string.title_explore;
                break;
            case 2:
                titleId = R.string.title_stream;
                break;
        }

        String title = getString(titleId);
        EasyTracker.getTracker().trackView(title);
        LOGD("Tracker",title);
    }

    @Override
    public void onPageScrollStateChanged(int i) {

    }

    @Override
    public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
        mViewPage.setCurrentItem(tab.getPosition());
    }

    @Override
    public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {

    }

    @Override
    public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {

    }
}
